import { useUserStore, useSelectOptionsStore } from "@/store/index";
import { ElMessage } from "element-plus";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { getDateAnd7DaysAgo, levelTransform } from "@/utils/index";
import {
  getOperateTypeLabel,
  getOrderStatusLabel,
  getSelApplyListLabel,
  getAuditStatusLabel,
  getChannelStatusLabel,
  OPERATE_TYPES,
} from "@/utils/selectOptions";

import {
  reqSelMerchant,
  reqModifyMerchant,
  reqChannelInterface,
  reqSelMerchantList,
  reqSelApplyList,
  reqLogin,
  reqIndex,
  reqSelDetailList,
  reqModifyWithdrawalAudit,
  reqSelWithdrawalAuditList,
  reqModifyUCStatus,
  reqModifyMerchantMargin,
} from "@/api/index";

export const useSourceApplyApproval = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const tableData1 = ref([]);
  const tableConfigData1 = ref([
    {
      prop: "busiId",
      label: "商戶號",
    },
    {
      prop: "country",
      label: "國別",
    },
    {
      prop: "payMethod",
      label: "貨幣",
    },
    {
      prop: "type",
      label: "类别",
    },
    {
      prop: "currency",
      label: "支付方式",
    },
    {
      prop: "status",
      label: "狀態",
    },
    {
      prop: "verify",
      label: "操作",
    },
    {
      prop: "costUpdate",
      label: "費用更新",
    },
    // {
    //   prop: "referUse",
    //   label: "對接文檔",
    // },
  ]);

  // const tableData2 = ref([]);
  // const tableConfigData2 = ref([
  //   {
  //     prop: "busiId",
  //     label: "商戶號",
  //   },
  //   {
  //     prop: "country",
  //     label: "國別",
  //   },
  //   {
  //     prop: "currency",
  //     label: "貨幣",
  //   },
  //   {
  //     prop: "type",
  //     label: "类别",
  //   },
  //   {
  //     prop: "payMethod",
  //     label: "支付方式",
  //   },
  //   {
  //     prop: "constantCost",
  //     label: "固定費用",
  //   },
  //   {
  //     prop: "priceRate",
  //     label: "費率",
  //   },
  //   {
  //     prop: "priceValue",
  //     label: "費用",
  //   },
  //   // {
  //   //   prop: "getMethod",
  //   //   label: "結算方式",
  //   // },
  //   {
  //     prop: "status",
  //     label: "狀態",
  //   },
  //   {
  //     prop: "costUpdate",
  //     label: "費用更新",
  //   },
  //   {
  //     prop: "verify",
  //     label: "审核",
  //   },
  // ]);

  // const updateCost = async (row) => {
  //   loading.value = true;
  //   clog("更新费用参数：", row);
  //   const res = await reqModifyUserCost(row);
  //   clog("更新费用接口返回：", res);
  //   loading.value = false;
  //   ElMessage.success("更新成功!");
  //   initData({
  //     page: 1,
  //     level: 1,
  //   });
  // };
  const verifyIt = async (row) => {
    loading.value = true;
    clog("审核参数：", row);
    const res = await reqModifyUCStatus(row);
    clog("审核接口返回：", res);
    loading.value = false;
    ElMessage.success("审核成功!");
    initData({
      page: 1,
      level: 1,
    });
  };
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    initData({
      page: pageInfo.value.currentPage,
      user_id: userId,
    });
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    initData({
      page: pageInfo.value.currentPage,
      user_id: userId,
    });
  };

  const initData = async ({ level, user_id, page } = {}) => {
    loading.value = true;
    try {
      const res = await reqSelApplyList({
        ouser_id: userStore.ouser_id,
        user_id: user_id || "",
        page,
      });
      clog("渠道申请列表：", res);
      tableData1.value = res.data.map((item) => ({
        ...item,
        busiId: item.user_id,
        country: item.country,
        currency: item.channel_code,
        type: item.type === 1 ? "代付" : "代收",
        payMethod: item.currency,
        status: getSelApplyListLabel(item.status),
        statusValue: item.status,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);

      // tableData2.value = res.data
      //   .filter((item) => item.type === 2)
      //   .map((item) => ({
      //     busiId: item.user_id,
      //     country: item.country,
      //     currency: item.pay_bank_code,
      //     type: "代收",
      //     payMethod: item.currency,
      //     constantCost: item.cost,
      //     priceRate: item.rate,
      //     priceValue: (parseFloat(item.cost) * parseFloat(item.rate)).toFixed(
      //       2
      //     ),
      //     status: getOrderStatusLabel(item.status),
      //     statusValue: item.status,
      //   }));
      loading.value = false;
    } catch (err) {
      loading.value = false;
      clog("渠道申请列表接口报错：", err);
    }
  };
  const router = useRouter();
  const tmpParamId = router.currentRoute.value.params.id;
  const userId = tmpParamId.includes(":id") ? "" : tmpParamId;
  initData({
    page: 1,
    user_id: userId,
  });
  return {
    loading,
    tableConfigData1,
    tableData1,
    verifyIt,
    initData,
    pageInfo,
    prevPage,
    nextPage,
  };
};

export const useSourceApiSum = () => {
  const loading = ref(false);
  const tableData = ref([]);
  const tableDataDisplay = ref([]);
  const tableConfigData = ref([
    {
      prop: "country",
      label: "國別",
      width: 60,
    },
    {
      prop: "currency",
      label: "貨幣",
      width: 60,
    },
    {
      prop: "type",
      label: "類別",
      width: 60,
    },
    {
      prop: "channel_code",
      label: "渠道編碼",
      width: 90,
    },
    {
      prop: "pay_type_code_name",
      label: "支付方式",
      width: 90,
    },
    {
      prop: "cost",
      label: "固定費用",
      width: 90,
    },
    {
      prop: "rate",
      label: "費率",
      width: 60,
    },
    {
      prop: "settlement_method",
      label: "結算方式（T）",
    },
    {
      prop: "status",
      label: "狀態",
    },
    {
      prop: "levelLabel",
      label: "商戶等級",
    },
    {
      prop: "changeStar",
      label: "操作",
    },
  ]);
  const pageInfo = ref({
    totalPage: 0,
    currentPage: 1,
    pageSize: 10,
  });

  const initData = async () => {
    loading.value = true;
    const userStore = useUserStore();
    try {
      const res = await reqChannelInterface(userStore.ouser_id);
      clog("渠道接口列表：", res);
      const tmpData = res.bdata.concat(res.cdata);
      tableData.value = tmpData.map((item) => {
        return {
          ...item,
          levelLabel: levelTransform(item.level),
          type: item.bid ? "代付" : "代收",
          status: getChannelStatusLabel(item.status),
          statusValue: item.status,
        };
      });
      pageInfo.value.totalPage = Math.ceil(
        tmpData.length / pageInfo.value.pageSize
      );
      setTableDataDisplay(pageInfo.value.currentPage, pageInfo.value.pageSize);
      loading.value = false;
    } catch (err) {
      loading.value = false;
      clog("渠道接口列表接口报错：", err);
    }
  };
  const prevPage = () => {
    if (pageInfo.value.currentPage > 1) {
      pageInfo.value.currentPage--;
      setTableDataDisplay(pageInfo.value.currentPage, pageInfo.value.pageSize);
    }
  };
  const nextPage = () => {
    if (pageInfo.value.currentPage < pageInfo.value.totalPage) {
      pageInfo.value.currentPage++;
      setTableDataDisplay(pageInfo.value.currentPage, pageInfo.value.pageSize);
    }
  };
  const setTableDataDisplay = (page, pageSize) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = page * pageSize;
    tableDataDisplay.value = tableData.value.slice(startIndex, endIndex);
  };
  initData();
  return {
    loading,
    tableConfigData,
    initData,
    pageInfo,
    prevPage,
    nextPage,
    tableDataDisplay,
    // updateStatus,
  };
};

export const useMerchantInfoUpdate = () => {
  const loading = ref(false);
  const level = ref(0);
  const busiId = ref("");
  const countryList = ref([]);
  const countryPromiseMoneyList = ref([]);
  const countryListUI = computed(() => {
    return countryList.value.filter(
      (countryItem) =>
        countryPromiseMoneyList.value.findIndex(
          (cItem) => cItem.country === countryItem.value
        ) === -1
    );
  });

  const infoForm = ref({
    companyName: "",
    withdrawBankName: "",
    licenseNumber: "",
    withdrawAccountName: "",
    contactPerson: "",
    withdrawAccountNumber: "",
    contactPhone: "",
    withdrawCurrency: "",
    contactEmail: "",
    settlementRate: "",
    // insurance: "",
    // country: "",
    // countryAddtion: "",
  });
  const rules = ref({
    companyName: [
      { required: true, message: "請輸入公司名稱", trigger: "blur" },
      {
        min: 2,
        max: 50,
        message: "公司名稱長度需介於 2 到 50 字",
        trigger: "blur",
      },
    ],
    withdrawBankName: [
      { required: true, message: "請輸入提現銀行名稱", trigger: "blur" },
      {
        min: 2,
        max: 50,
        message: "提現銀行名稱長度需介於 2 到 50 字",
        trigger: "blur",
      },
    ],
    licenseNumber: [
      { required: true, message: "請輸入公司執照號碼", trigger: "blur" },
    ],
    withdrawAccountName: [
      { required: true, message: "請輸入提現賬戶名稱", trigger: "blur" },
      {
        min: 2,
        max: 50,
        message: "提現賬戶名稱長度需介於 2 到 50 字",
        trigger: "blur",
      },
    ],
    contactPerson: [
      { required: true, message: "請輸入聯繫人", trigger: "blur" },
      {
        min: 2,
        max: 50,
        message: "聯繫人長度需介於 2 到 50 字",
        trigger: "blur",
      },
    ],
    withdrawAccountNumber: [
      { required: true, message: "請輸入提現銀行帳戶號", trigger: "blur" },
      {
        min: 10,
        max: 20,
        message: "提現銀行帳戶號長度需介於 10 到 20 字",
        trigger: "blur",
      },
    ],
    contactPhone: [
      { required: true, message: "請輸入聯繫電話", trigger: "blur" },
    ],
    withdrawCurrency: [
      { required: true, message: "請選擇提現貨幣", trigger: "change" },
    ],
    contactEmail: [
      { required: true, message: "請輸入聯繫郵箱", trigger: "blur" },
      { type: "email", message: "郵箱格式不正確", trigger: "blur" },
    ],
    settlementRate: [
      { required: true, message: "請輸入結算匯率", trigger: "blur" },
    ],
    // insurance: [{ required: true, message: "請輸入保證金", trigger: "blur" }],
  });
  const validateInsurance = () => {
    const tmpIndex = countryPromiseMoneyList.value.findIndex(
      (item) => !item.money
    );
    return tmpIndex > -1 ? false : true;
  };

  const submitForm = (formDom) => {
    if (!validateInsurance()) {
      ElMessage.error("保證金必填!");
      return;
    }
    formDom.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        clog("商户信息修改参数：", {
          user_id: busiId.value,
          company_name: infoForm.value.companyName,
          license_code: infoForm.value.licenseNumber,
          contacts: infoForm.value.contactPerson,
          phone: infoForm.value.contactPhone,
          mail: infoForm.value.contactEmail,
          bank_name: infoForm.value.withdrawBankName,
          account_name: infoForm.value.withdrawAccountName,
          account: infoForm.value.withdrawAccountNumber,
          currency: infoForm.value.withdrawCurrency,
          exchange_rate: infoForm.value.settlementRate,
        });
        try {
          const res = await reqModifyMerchant({
            user_id: busiId.value,
            company_name: infoForm.value.companyName,
            license_code: infoForm.value.licenseNumber,
            contacts: infoForm.value.contactPerson,
            phone: infoForm.value.contactPhone,
            mail: infoForm.value.contactEmail,
            bank_name: infoForm.value.withdrawBankName,
            account_name: infoForm.value.withdrawAccountName,
            account: infoForm.value.withdrawAccountNumber,
            currency: infoForm.value.withdrawCurrency,
            exchange_rate: infoForm.value.settlementRate,
          });
          clog("修改商户信息：", res);
          if (countryPromiseMoneyList.value.length > 0) {
            const res2 = await reqModifyMerchantMargin({
              user_id: busiId.value,
              data: JSON.stringify(
                countryPromiseMoneyList.value.map((item) => ({
                  currency: item.country,
                  risk_margin_set: item.money,
                  ubid: item.ubid,
                }))
              ),
            });
            clog("修改商户保证金：", res2);
          }
          loading.value = false;
          ElMessage.success("修改成功!");
        } catch (err) {
          clog("修改商户信息接口报错：", err);
          loading.value = false;
        }
      }
    });
  };
  const setInfoForm = (data) => {
    if (!data) {
      busiId.value = merchantId;
      return;
    }
    busiId.value = String(data.user_id);
    infoForm.value = {
      companyName: data.company_name,
      account: data.account,
      withdrawBankName: data.bank_name,
      licenseNumber: data.license_code,
      withdrawAccountName: data.account_name,
      contactPerson: data.contacts,
      withdrawAccountNumber: data.account,
      contactPhone: data.phone,
      withdrawCurrency: data.currency,
      contactEmail: data.mail,
      settlementRate: data.exchange_rate,
      // insurance: "",
      // country: "",
      // countryAddition: "",
    };
  };
  const setCountryMoney = (data, user_risk_margin) => {
    countryList.value = data.map((item) => ({
      label: item.currency,
      value: item.currency,
    }));
    countryPromiseMoneyList.value = user_risk_margin.map((item) => ({
      country: item.currency,
      money: item.risk_margin_set,
      ubid: item.ubid,
    }));
  };
  const initData = async (userId) => {
    if (!userId) {
      return;
    }
    loading.value = true;
    try {
      const res = await reqSelMerchant(userId || "");
      clog("商户信息更新：", res);
      setInfoForm(res.data[0]);
      level.value = res.level[0]?.level;
      setCountryMoney(res.data, res.user_risk_margin);
      loading.value = false;
    } catch (err) {
      clog("商户信息更新接口报错：", err);
      loading.value = false;
    }
  };
  const router = useRouter();
  const tmpParamId = router.currentRoute.value.params.id;
  // const merchantId = router.currentRoute.value.params.id || "1004";
  const merchantId = tmpParamId.includes(":id") ? "" : tmpParamId;
  console.log("merchantId", merchantId);
  initData(merchantId);
  return {
    loading,
    level,
    busiId,
    // countries,
    infoForm,
    rules,
    // countryAddtionChooseVisible,
    submitForm,
    // showCountryAddtion,
    // hideCountryAddition,
    countryListUI,
    countryPromiseMoneyList,
  };
};

export const useLogin = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const router = useRouter();

  const form = ref({
    email: "",
    password: "",
    googleCode: "",
  });
  const formRules = ref({
    email: [{ required: "true", message: "賬戶不能爲空", trigger: "blur" }],
    password: [{ required: "true", message: "密碼不能爲空", trigger: "blur" }],
    googleCode: [
      { required: "true", message: "谷歌驗證器不能为空", trigger: "blur" },
    ],
  });
  const submitForm = (formDom) => {
    formDom.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const loginRes = await reqLogin({
            mail: form.value.email,
            code: form.value.googleCode,
            password: form.value.password,
          });
          loading.value = false;
          clog("登录接口返回：", loginRes);
          userStore.setUserInfo(loginRes);
          ElMessage.success("登錄成功!");
          router.push("/home");
        } catch (e) {
          clog("登录接口异常：", e);
          loading.value = false;
        }
      }
    });
  };
  return {
    form,
    formRules,
    submitForm,
    loading,
  };
};

export const useHome = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const initData = async ({ user_id, currency } = {}) => {
    loading.value = true;
    try {
      const indexRes = await reqIndex({
        user_id: user_id || "",
        currency: currency || "",
        ouser_id: userStore.ouser_id,
      });
      clog("首页接口返回：", indexRes);
      if (indexRes?.data?.length) {
        setCardInfoList(indexRes.data[0]);
      }
      loading.value = false;
    } catch (err) {
      clog("首页接口报错：", err);
      loading.value = false;
    }
  };
  initData({
    currency: "VND",
  });
  const searchFormConfig = ref({
    currency: {
      name: "貨幣",
    },
    busiId: {
      name: "商戶號",
    },
    // sourceEncoding: {
    //   name: "渠道編碼",
    // },
  });

  const setCardInfoList = (data) => {
    const { amount, freeze_amount, risk_margin, diff } = data;
    const amountValue = amount ? parseFloat(amount) : 0;
    const freezeAmountValue = freeze_amount ? parseFloat(freeze_amount) : 0;
    const riskMarginValue = risk_margin ? parseFloat(risk_margin) : 0;
    const diffValue = diff ? parseFloat(diff) : 0;
    const availableAmountValue =
      amountValue + freezeAmountValue + riskMarginValue + diffValue;
    cardInfoList.value[4].value = `$${diffValue.toFixed(2)}`;
    cardInfoList.value[3].value = `$${amountValue.toFixed(2)}`;
    cardInfoList.value[2].value = `$${freezeAmountValue.toFixed(2)}`;
    cardInfoList.value[1].value = `$${riskMarginValue.toFixed(2)}`;
    cardInfoList.value[0].value = `$${availableAmountValue.toFixed(2)}`;
  };
  const cardInfoList = ref([
    {
      label: "帳戶金額",
      value: "$0",
    },
    {
      label: "風險保證金",
      value: "$0",
    },
    {
      label: "凍結金額",
      value: "$0",
    },
    {
      label: "可用餘額",
      value: "$0",
    },
    {
      label: "合計費用差額",
      value: "$0",
    },
  ]);

  return {
    loading,
    searchFormConfig,
    cardInfoList,
    initData,
  };
};

export const useDetailOrderQuery = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const selectOptionsStore = useSelectOptionsStore();
  const initData = async ({
    user_id,
    currency,
    type,
    startdata,
    enddata,
    platform_order,
    channel_order,
    merchant_order,
    status,
    page,
    ouser_id,
  } = {}) => {
    try {
      loading.value = true;
      const res = await reqSelDetailList({
        user_id: user_id || "",
        currency: currency || "",
        type: type || "",
        startdata: startdata || "",
        enddata: enddata || "",
        platform_order: platform_order || "",
        channel_order: channel_order || "",
        merchant_order: merchant_order || "",
        status: status || "",
        page: page || "",
        ouser_id: ouser_id || "",
      });
      loading.value = false;
      clog("订单详情查询接口返回：", res);
      tableData.value = res.data.map((item) => {
        return {
          platformOrderId: item.platform_order,
          merchantOrderId: item.merchant_order,
          orderType: getOperateTypeLabel(item.type),
          money: item.order_amount,
          payBefore: item.platform_cost,
          cost: item.merchant_cost,
          status: getOrderStatusLabel(item.status),
          consumeDate: item.created_at,
          saveDate: item.receipt_time,
          costDistance: item.merchant_cost - item.platform_cost,
          busiId: item.user_id,
        };
      });
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
    } catch (err) {
      clog("订单详情查询接口异常：", err);
      loading.value = false;
    }
  };
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const { today, sevenDaysAgo } = getDateAnd7DaysAgo();
  const searchFormConfig = ref({
    busiId: {
      name: "商戶號",
      order: 1,
    },
    currency: {
      name: "貨幣",
      order: 2,
    },
    operateType: {
      name: "類型",
      order: 3,
    },
    date: {
      name: "日期",
      order: 4,
    },
    platformOrderId: {
      name: "平臺訂單號",
      order: 5,
    },
    merchantOrderId: {
      name: "商戶訂單號",
      order: 6,
    },
    orderStatus: {
      name: "狀態",
      order: 7,
    },
    sourceOrderId: {
      name: "渠道訂單號",
      order: 8,
    },
  });

  const tableData = ref([]);
  const tableConfigData = ref([
    {
      prop: "busiId",
      label: "商户号",
    },
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    {
      prop: "merchantOrderId",
      label: "商戶訂單號",
    },
    // {
    //   prop: "sourceOrderId",
    //   label: "渠道訂單號",
    // },
    {
      prop: "orderType",
      label: "類型",
    },
    {
      prop: "money",
      label: "金額",
    },
    {
      prop: "payBefore",
      label: "平台費用",
    },
    {
      prop: "cost",
      label: "費用",
    },
    {
      prop: "status",
      label: "狀態",
    },
    {
      prop: "consumeDate",
      label: "訂單時間",
    },
    {
      prop: "saveDate",
      label: "記帳時間",
    },
    {
      prop: "costDistance",
      label: "费用差额",
    },
  ]);

  if (selectOptionsStore.currencies.length > 0) {
    const activeCurrency = selectOptionsStore.currencies[0].value;
    initData({
      ouser_id: userStore.ouser_id,
      currency: activeCurrency,
      type: OPERATE_TYPES[2].value, // 操作类型：充值
      startdata: sevenDaysAgo.dateStr,
      enddata: today.dateStr,
      page: "1",
    });
  }

  return {
    loading,
    searchFormConfig,
    tableData,
    tableConfigData,
    initData,
    pageInfo,
  };
};

export const useBusiWithdrawApproval = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    initData(pageInfo.value.currentPage);
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    initData(pageInfo.value.currentPage);
  };
  const initData = async (page) => {
    loading.value = true;
    try {
      const res = await reqSelWithdrawalAuditList({
        ouser_id: userStore.ouser_id,
        type: "1",
        page,
      });
      loading.value = false;
      clog("提现审批列表接口返回：", res);
      tableData.value = res.data.map((item) => {
        return {
          id: item.withdrawal_id,
          platformOrderId: item.platform_order,
          currency: item.currency,
          receiveUser: item.acc_name,
          bankName: item.bank_name,
          bankAccount: item.acc_no,
          amount: item.order_amount,
          cost: item.merchant_cost,
          orderTime: item.created_at,
          payRate: item.exchange_rate,
          status: getAuditStatusLabel(item.auditing_status),
          statusValue: item.auditing_status,
        };
      });
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
    } catch (err) {
      loading.value = false;
      clog("提现审批列表接口报错：", err);
    }
  };
  initData("1");
  const tableData = ref([]);
  const tableConfigData = ref([
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "receiveUser",
      label: "收款人姓名",
    },
    {
      prop: "bankName",
      label: "銀行名稱",
    },
    {
      prop: "bankAccount",
      label: "銀行帳戶",
    },
    {
      prop: "amount",
      label: "金額",
      width: 80,
    },
    {
      prop: "cost",
      label: "費用",
      width: 80,
    },
    {
      prop: "orderTime",
      label: "訂單時間",
    },
    {
      prop: "payRate",
      label: "結算匯率",
    },
    {
      prop: "status",
      label: "狀態",
      width: 60,
    },
    {
      prop: "verify",
      label: "選擇狀態",
    },
  ]);

  const modifyWithdrawalAudit = async (info) => {
    loading.value = true;
    try {
      const res = await reqModifyWithdrawalAudit({
        ouser_id: userStore.ouser_id,
        withdrawal_id: info.id,
        auditing_status: info.statusValue,
      });
      clog("modifyWithdrawalAudit res: ", res);
      ElMessage.success("修改成功!");
      loading.value = false;
      initData("1");
    } catch (err) {
      loading.value = false;
      clog("modifyWithdrawalAudit error: ", err);
    }
  };

  return {
    initData,
    loading,
    tableData,
    tableConfigData,
    modifyWithdrawalAudit,
    pageInfo,
    prevPage,
    nextPage,
  };
};

export const useBusiInfoQuery = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const initData = async ({ company_name, mail, level, page, user_id }) => {
    loading.value = true;
    clog("商户信息查询参数：", {
      ouser_id: userStore.ouser_id,
      company_name: company_name || "",
      mail: mail || "",
      level: level || "",
      user_id: user_id || "",
      page,
    });
    try {
      const res = await reqSelMerchantList({
        ouser_id: userStore.ouser_id,
        company_name: company_name || "",
        mail: mail || "",
        level: level || "",
        user_id: user_id || "",
        page,
      });
      clog("商户信息查询：", res);
      tableData.value = res.data.map((item) => ({
        ...item,
        email: item.mail,
        companyName: item.company_name,
        certificateNo: item.license_code,
        merchantId: item.user_id,
        contactUser: item.contacts,
        contactPhone: item.phone,
        contactEmail: item.contacts_mail,
        merchantLevel: item.level,
        merchantLevelLabel: levelTransform(item.level),
        exchange_rate: item.exchange_rate,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
      loading.value = false;
    } catch (err) {
      clog("商户信息查询接口报错：", err);
      loading.value = false;
    }
  };
  initData({
    page: "1",
  });
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    initData({
      page: pageInfo.value.currentPage,
    });
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    initData({
      page: pageInfo.value.currentPage,
    });
  };
  const searchFormConfig = ref({
    busiId: {
      name: "商戶號",
    },
    companyName: {
      name: "公司名",
    },
    email: {
      name: "註冊郵箱",
    },
    merchantLevel: {
      name: "商戶等級",
    },
  });

  const tableData = ref([]);
  const tableConfigData = ref([
    {
      prop: "email",
      label: "註冊郵箱",
    },
    {
      prop: "companyName",
      label: "公司名",
    },
    {
      prop: "certificateNo",
      label: "執照編號",
    },
    {
      prop: "merchantId",
      label: "商戶號",
    },
    {
      prop: "contactUser",
      label: "聯繫人",
    },
    {
      prop: "contactPhone",
      label: "聯繫電話",
    },
    {
      prop: "contactEmail",
      label: "聯繫郵箱",
    },
    {
      prop: "merchantLevelLabel",
      label: "商戶等級",
    },
    {
      prop: "exchange_rate",
      label: "結算匯率",
    },
    {
      prop: "changeStar",
      label: "操作",
    },
    {
      prop: "checkDetail",
      label: "查詢詳情",
    },
    {
      prop: "sourceActive",
      label: "已開通渠道",
    },
    // {
    //   prop: "costUpdate",
    //   label: "費用更新",
    // },
    {
      prop: "exchange_rate",
      label: "結算匯率",
    },
  ]);
  return {
    loading,
    searchFormConfig,
    tableData,
    tableConfigData,
    initData,
    pageInfo,
    prevPage,
    nextPage,
  };
};

export const useBusiAgentPayApproval = () => {
  const loading = ref(false);
  const tableData = ref([]);
  const userStore = useUserStore();
  const tableConfigData = ref([
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    // {
    //   prop: "merchantOrderId",
    //   label: "商家訂單號",
    // },
    // {
    //   prop: "sourceOrderId",
    //   label: "渠道訂單號",
    // },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "receiveUser",
      label: "收款人姓名",
    },
    {
      prop: "bankName",
      label: "銀行名稱",
    },
    {
      prop: "bankAccount",
      label: "銀行帳戶",
    },
    {
      prop: "amount",
      label: "金額",
      width: 80,
    },
    {
      prop: "cost",
      label: "費用",
      width: 80,
    },
    // {
    //   prop: "description",
    //   label: "描述",
    //   width: 80,
    // },
    {
      prop: "orderTime",
      label: "訂單時間",
    },
    {
      prop: "status",
      label: "審批類型",
    },
    {
      prop: "verify",
      label: "操作",
    },
  ]);
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });

  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    initData(pageInfo.value.currentPage);
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    initData(pageInfo.value.currentPage);
  };
  const initData = async (page) => {
    loading.value = true;
    const userStore = useUserStore();
    try {
      const res = await reqSelWithdrawalAuditList({
        ouser_id: userStore.ouser_id,
        type: "2",
        page,
      });
      loading.value = false;
      clog("代付审批列表接口返回：", res);
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
      tableData.value = res.data.map((item) => {
        return {
          id: item.withdrawal_id,
          platformOrderId: item.platform_order,
          currency: item.currency,
          receiveUser: item.acc_name,
          bankName: item.bank_name,
          bankAccount: item.acc_no,
          amount: item.order_amount,
          cost: item.merchant_cost,
          orderTime: item.created_at,
          status: getAuditStatusLabel(item.auditing_status),
          statusValue: item.auditing_status,
        };
      });
    } catch (err) {
      clog("代付审批列表接口报错：", err);
      loading.value = false;
    }
  };
  initData(1);
  const modifyWithdrawalAudit = async (info) => {
    loading.value = true;
    try {
      const res = await reqModifyWithdrawalAudit({
        ouser_id: userStore.ouser_id,
        withdrawal_id: info.id,
        auditing_status: info.statusValue,
      });
      clog("modifyWithdrawalAudit res: ", res);
      ElMessage.success("修改成功!");
      loading.value = false;
      initData("1");
    } catch (err) {
      loading.value = false;
      clog("modifyWithdrawalAudit error: ", err);
    }
  };

  return {
    loading,
    tableData,
    tableConfigData,
    pageInfo,
    prevPage,
    nextPage,
    modifyWithdrawalAudit,
  };
};
